package org.achao.server;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author achao
 * @description websocket 简单使用
 * @date 2023/9/29 22:54
 */
@Component
@ServerEndpoint("/socket/{uuid}")
public class WebSocketDemoServer {

    /**
     * 存储当前对象
     **/
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    /**
     * 创建websocket连接
     *
     * @param session
     * @param uuid
     */
    @OnOpen
    public void onOpen(@PathParam("uuid") String uuid, Session session) {
        System.out.println(uuid + "打开了websocket双向通道...");
        sessionMap.put(uuid, session);
        try {
            session.getBasicRemote().sendText("欢迎来到achao教学小课堂...");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭websocket连接
     *
     * @param uuid
     */
    @OnClose
    public void onClose(@PathParam("uuid") String uuid) {
        System.out.println(uuid + "断开了websocket双向通道...");
    }

    /**
     * 异常断开websocket连接
     *
     * @param error
     */
    @OnError
    public void onError(Throwable error) {
        System.out.println("websocket异常断开连接...");
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("服务器接受到的消息为【" + message + "】");
    }

    /**
     * 系统群发消息
     */
    public void sendMessageAll() {
        Collection<Session> values = sessionMap.values();
        try {
            for (Session session : values) {
                session.getBasicRemote().sendText("群发消息：大家好呀我是achao~");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
